using System;
using System.IO;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Collections;
using System.Windows.Forms;
using System.Resources;
using System.Diagnostics;
using System.Net;
using System.Data;

using OpenNETCF.Win32;
using WinCE;
using MSHelpLib;
using MSHelpLib.BaseCode;
using MSHelpLib.CHM.Decoding;
using MSHelpLib.HXS.Decoding;
using MruMenu;

[assembly: AssemblyTitle("PPCHelpReader.NET")]
[assembly: AssemblyDescription("PPC HelpReader.NET for Windows CE - A Viewer for CHM & HXS help files")]

namespace PPCHelpReader
{
	/// <summary>
	/// Summary description for Form1.
	/// </summary>
	public class PPCHelpReader : System.Windows.Forms.Form
	{
		/// <summary>
		/// This is the location of the temp directory to be used.
		/// </summary>	
		private const string TempDirDefault= @"\Temp";
		private string TempDir = TempDirDefault;

		/// <summary>
		/// If true, the temp directory will be deleted before each new page is loaded thus saving space
		/// If false, the temp directory will NOT be deleted, allowing common files in the HelpFile to persist and 
		/// increase the loading speed.
		/// </summary>
		private bool bWipeTempDir=false;

		/// <summary>
		/// =True when Contents Tab has been init
		/// </summary>
		private bool m_bContentsInit=false;		

		/// <summary>
		/// =True when Index Tab has been init
		/// </summary>
		private bool m_bIndexInit=false;

		/// <summary>
		/// =True when Search Tab has been init
		/// </summary>
		private bool m_bSearchInit=false;

		/// <summary>
		/// =True when we are moving selection and do not want to act on selection
		/// </summary>
		private bool m_bMovingSelection=false;

		/// <summary>
		/// ==True when we are in DisplayPage Loop
		/// </summary>
		private bool m_bInLoop=false;

		/// <summary>
		///  Search Results list
		/// </summary>
		private SearchResultsTable _hits = null;

		/// <summary>
		/// Search order
		/// </summary>
		private bool ascSort = false;

		/// <summary>
        /// Holds the Help file object
		/// </summary>		
		private MSHelpLib.HelpSystem helpSystem=null;

        private string m_LocationString = "";
		private string LocationString
        {
            get
            {
                return m_LocationString;
            }
            set
            {
                m_LocationString = value;
                menuLocation.Enabled = !String.IsNullOrEmpty(m_LocationString);
            }
        }
		/// <summary>
		/// Used with the Input Panel to hold the height of the tab page
		/// </summary>
		private int TabOriginalHeight;
		private Rectangle VisibleRect;

		/// <summary>
		/// Holds the index data
		/// </summary>
		public ArrayList _arrIndex = null;

		private System.Windows.Forms.MenuItem mnuFile;
		private System.Windows.Forms.MenuItem mnuOpen;
		private System.Windows.Forms.MenuItem mnuClose;
		private System.Windows.Forms.MenuItem mnuHelp;
		private System.Windows.Forms.MenuItem mnuAbout;
		private System.Windows.Forms.TabControl tabControl1;
		private System.Windows.Forms.TabPage tabContents;
		private System.Windows.Forms.TabPage tabSearch;
		private System.Windows.Forms.TabPage tabIndex;		
		private System.Windows.Forms.TextBox txtIndex;
		private System.Windows.Forms.TextBox txtSearch;
		private System.Windows.Forms.Button btnSearch;
		private System.Windows.Forms.ColumnHeader colTitle;
		private System.Windows.Forms.ColumnHeader colRank;
		private System.Windows.Forms.MainMenu mainMenu1;
		private Microsoft.WindowsCE.Forms.InputPanel inputPanel1=null;
		private System.Windows.Forms.TreeView tvContents;
		private System.Windows.Forms.ListBox lbIndex;
		private System.Windows.Forms.ListView lvSearch;
		private System.Windows.Forms.MenuItem mnuOptions;
		private System.Windows.Forms.MenuItem menuItem1;
		private System.Windows.Forms.MenuItem menuItem3;
		private System.Windows.Forms.MenuItem mnuRecent;
		private System.Windows.Forms.ColumnHeader colLocation;
        private MruMenu.MruMenu mruMenu = null;
		private FileInfo fi=null;        
		private System.Windows.Forms.Button btnGo;
		private System.Windows.Forms.MenuItem menuLocation;        
        private Label lbInfo1;
        private Label lbInfo2;        
        private Label lbInfo3;
        private ProgressBar PrgBar = null;
        private OpenFileDialog openFileDialog1;

        /// <summary>
        /// Initializes a new instance of the <see cref="PPCHelpReader"/> class.
        /// </summary>
        /// <param name="args">The args.</param>
		public PPCHelpReader(string[] args)
		{
            //
			// Required for Windows Form Designer support
			//
			InitializeComponent();            
            LocationString = "";

            // Create an input panel - We need to do it here, as on PPC's with hardware keyboard, this will throw exception
			try
			{
				this.inputPanel1 = new Microsoft.WindowsCE.Forms.InputPanel();				
				this.inputPanel1.EnabledChanged += new System.EventHandler(this.inputPanel1_EnabledChanged);
			}
			catch
			{
				inputPanel1=null;
			}

			// Make sure controls are Auto-positioned depending on screen size & orientation.
			this.tabControl1.Size = new System.Drawing.Size(this.ClientRectangle.Width, this.ClientRectangle.Height);

			this.tvContents.Location=new Point(0,0);
			this.tvContents.Size=new Size(this.ClientRectangle.Width, this.ClientRectangle.Height);

			txtIndex.Location=new Point(0,0);
			txtIndex.Size=new Size(this.ClientRectangle.Width-20,20);
			btnGo.Location=new Point(this.ClientRectangle.Width-20,0);
			btnGo.Size=new Size(20,20);
			this.lbIndex.Location=new Point(0,20);
			this.lbIndex.Size=new Size(this.ClientRectangle.Width, this.ClientRectangle.Height-20);

			txtSearch.Location=new Point(0,0);
			txtSearch.Size=new Size(this.ClientRectangle.Width-56,20);
			btnSearch.Location=new Point(this.ClientRectangle.Width-56,0);
			btnSearch.Size=new Size(56,20);
			lvSearch.Location=new Point(0,20);
			lvSearch.Size=new Size(this.ClientRectangle.Width,this.ClientRectangle.Height-20);

			this.colTitle.Width=(lvSearch.Width/4)*2;
			this.colLocation.Width=(lvSearch.Width/4);
			this.colRank.Width=(lvSearch.Width/4)-2;

			// More Tab Control init stuff
			TabOriginalHeight = tabControl1.Height;
			if (inputPanel1!=null)
			{
				VisibleRect = inputPanel1.VisibleDesktop;
			}
			tabControl1.TabPages.Clear();
			tabControl1.Enabled=false;
			tabControl1.Visible=false;
			Update();
            
            int InfoHeight = (Height-PrgBar.Height) / 3;
            lbInfo1.Top = 0;
            lbInfo1.Height = InfoHeight;
            lbInfo2.Top = lbInfo1.Top+lbInfo1.Height;
            lbInfo2.Height = InfoHeight;
            lbInfo3.Top = lbInfo2.Top + lbInfo2.Height;
            lbInfo3.Height = InfoHeight;
            PrgBar.Top = lbInfo3.Top + lbInfo3.Height;

			Text="PPCHelpReader";
		
			// Create the MRU Menu class
            mruMenu = new MruMenu.MruMenu(mnuRecent, @"SOFTWARE\MSHelpReader.NET\MRU");
            mruMenu.MRUHandlerEvent += new MruMenu.MruMenu.MRUHandler(mruMenu_MRUHandlerEvent);
            mnuRecent.Enabled = (mnuRecent.MenuItems.Count > 0);
			
			// Load some parameters
			LoadParams();

            // Handle Parameters
			if ((args!=null) && (args.Length==1))
			{
				string Arg=args[0];
				FileInfo fi=new FileInfo(Arg);
				if ((fi.Extension.ToLower()==".chi") || (fi.Extension.ToLower()==".chq") ||(fi.Extension.ToLower()==".chq"))
					Arg=Arg.ToLower().Replace(fi.Extension.ToLower(),".chm");	
				if (fi.Extension.ToLower()==".hxi")
					Arg=Arg.ToLower().Replace(fi.Extension.ToLower(),".hxs");	
				this.OpenHelpFile(new FileInfo(Arg));
			}
			ShowProgress(false);
			tabControl1.Visible=false;
			tabControl1.Enabled=false;

		}

        /// <summary>
        /// MRUs the menu_ MRU handler event.
        /// </summary>
        /// <param name="number">The number.</param>
        /// <param name="FileName">Name of the file.</param>
		private void mruMenu_MRUHandlerEvent(int number, string FileName)
		{
			OpenHelpFile(new FileInfo(FileName));
		}

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose( bool disposing )
		{
			base.Dispose( disposing );
		}
		#region Windows Form Designer generated code
		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
            this.mainMenu1 = new System.Windows.Forms.MainMenu();
            this.mnuFile = new System.Windows.Forms.MenuItem();
            this.mnuOpen = new System.Windows.Forms.MenuItem();
            this.menuItem3 = new System.Windows.Forms.MenuItem();
            this.mnuRecent = new System.Windows.Forms.MenuItem();
            this.mnuOptions = new System.Windows.Forms.MenuItem();
            this.menuItem1 = new System.Windows.Forms.MenuItem();
            this.mnuClose = new System.Windows.Forms.MenuItem();
            this.menuLocation = new System.Windows.Forms.MenuItem();
            this.mnuHelp = new System.Windows.Forms.MenuItem();
            this.mnuAbout = new System.Windows.Forms.MenuItem();
            this.tabControl1 = new System.Windows.Forms.TabControl();
            this.tabContents = new System.Windows.Forms.TabPage();
            this.tvContents = new System.Windows.Forms.TreeView();
            this.tabSearch = new System.Windows.Forms.TabPage();
            this.lvSearch = new System.Windows.Forms.ListView();
            this.colTitle = new System.Windows.Forms.ColumnHeader();
            this.colLocation = new System.Windows.Forms.ColumnHeader();
            this.colRank = new System.Windows.Forms.ColumnHeader();
            this.btnSearch = new System.Windows.Forms.Button();
            this.txtSearch = new System.Windows.Forms.TextBox();
            this.tabIndex = new System.Windows.Forms.TabPage();
            this.lbIndex = new System.Windows.Forms.ListBox();
            this.btnGo = new System.Windows.Forms.Button();
            this.txtIndex = new System.Windows.Forms.TextBox();
            this.PrgBar = new System.Windows.Forms.ProgressBar();
            this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
            this.lbInfo1 = new System.Windows.Forms.Label();
            this.lbInfo2 = new System.Windows.Forms.Label();
            this.lbInfo3 = new System.Windows.Forms.Label();
            this.tabControl1.SuspendLayout();
            this.tabContents.SuspendLayout();
            this.tabSearch.SuspendLayout();
            this.tabIndex.SuspendLayout();
            this.SuspendLayout();
            // 
            // mainMenu1
            // 
            this.mainMenu1.MenuItems.Add(this.mnuFile);
            this.mainMenu1.MenuItems.Add(this.menuLocation);
            this.mainMenu1.MenuItems.Add(this.mnuHelp);
            // 
            // mnuFile
            // 
            this.mnuFile.MenuItems.Add(this.mnuOpen);
            this.mnuFile.MenuItems.Add(this.menuItem3);
            this.mnuFile.MenuItems.Add(this.mnuRecent);
            this.mnuFile.MenuItems.Add(this.mnuOptions);
            this.mnuFile.MenuItems.Add(this.menuItem1);
            this.mnuFile.MenuItems.Add(this.mnuClose);
            this.mnuFile.Text = "File";
            // 
            // mnuOpen
            // 
            this.mnuOpen.Text = "Open";
            this.mnuOpen.Click += new System.EventHandler(this.mnuOpen_Click);
            // 
            // menuItem3
            // 
            this.menuItem3.Text = "-";
            // 
            // mnuRecent
            // 
            this.mnuRecent.Text = "Recent ";
            // 
            // mnuOptions
            // 
            this.mnuOptions.Text = "Options";
            this.mnuOptions.Click += new System.EventHandler(this.mnuOptions_Click);
            // 
            // menuItem1
            // 
            this.menuItem1.Text = "-";
            // 
            // mnuClose
            // 
            this.mnuClose.Text = "Close";
            this.mnuClose.Click += new System.EventHandler(this.mnuClose_Click);
            // 
            // menuLocation
            // 
            this.menuLocation.Text = "Loc";
            this.menuLocation.Click += new System.EventHandler(this.menuLocation_Click);
            // 
            // mnuHelp
            // 
            this.mnuHelp.MenuItems.Add(this.mnuAbout);
            this.mnuHelp.Text = "Help";
            // 
            // mnuAbout
            // 
            this.mnuAbout.Text = "About...";
            this.mnuAbout.Click += new System.EventHandler(this.mnuAbout_Click);
            // 
            // tabControl1
            // 
            this.tabControl1.Controls.Add(this.tabContents);
            this.tabControl1.Controls.Add(this.tabSearch);
            this.tabControl1.Controls.Add(this.tabIndex);
            this.tabControl1.Dock = System.Windows.Forms.DockStyle.None;
            this.tabControl1.Location = new System.Drawing.Point(0, 0);
            this.tabControl1.Name = "tabControl1";
            this.tabControl1.SelectedIndex = 0;
            this.tabControl1.Size = new System.Drawing.Size(240, 268);
            this.tabControl1.TabIndex = 0;
            this.tabControl1.SelectedIndexChanged += new System.EventHandler(this.tabControl1_SelectedIndexChanged);
            // 
            // tabContents
            // 
            this.tabContents.Controls.Add(this.tvContents);
            this.tabContents.Location = new System.Drawing.Point(0, 0);
            this.tabContents.Name = "tabContents";
            this.tabContents.Size = new System.Drawing.Size(240, 245);
            this.tabContents.Text = "Contents";
            // 
            // tvContents
            // 
            this.tvContents.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
                        | System.Windows.Forms.AnchorStyles.Left)
                        | System.Windows.Forms.AnchorStyles.Right)));
            this.tvContents.Font = new System.Drawing.Font("Tahoma", 8F, System.Drawing.FontStyle.Regular);
            this.tvContents.Indent = 31;
            this.tvContents.Location = new System.Drawing.Point(0, 0);
            this.tvContents.Name = "tvContents";
            this.tvContents.Size = new System.Drawing.Size(236, 259);
            this.tvContents.TabIndex = 0;
            this.tvContents.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.tvContents_AfterSelect);
            // 
            // tabSearch
            // 
            this.tabSearch.Controls.Add(this.lvSearch);
            this.tabSearch.Controls.Add(this.btnSearch);
            this.tabSearch.Controls.Add(this.txtSearch);
            this.tabSearch.Location = new System.Drawing.Point(0, 0);
            this.tabSearch.Name = "tabSearch";
            this.tabSearch.Size = new System.Drawing.Size(232, 242);
            this.tabSearch.Text = "Search";
            // 
            // lvSearch
            // 
            this.lvSearch.Columns.Add(this.colTitle);
            this.lvSearch.Columns.Add(this.colLocation);
            this.lvSearch.Columns.Add(this.colRank);
            this.lvSearch.Dock = System.Windows.Forms.DockStyle.Fill;
            this.lvSearch.FullRowSelect = true;
            this.lvSearch.Location = new System.Drawing.Point(0, 46);
            this.lvSearch.Name = "lvSearch";
            this.lvSearch.Size = new System.Drawing.Size(232, 196);
            this.lvSearch.TabIndex = 0;
            this.lvSearch.View = System.Windows.Forms.View.Details;
            this.lvSearch.ItemActivate += new System.EventHandler(this.lvSearch_ItemActivate);
            this.lvSearch.ColumnClick += new System.Windows.Forms.ColumnClickEventHandler(this.lvSearch_ColumnClick);
            // 
            // colTitle
            // 
            this.colTitle.Text = "Title";
            this.colTitle.Width = 112;
            // 
            // colLocation
            // 
            this.colLocation.Text = "Location";
            this.colLocation.Width = 115;
            // 
            // colRank
            // 
            this.colRank.Text = "Rank";
            this.colRank.Width = 78;
            // 
            // btnSearch
            // 
            this.btnSearch.Dock = System.Windows.Forms.DockStyle.Top;
            this.btnSearch.Location = new System.Drawing.Point(0, 21);
            this.btnSearch.Name = "btnSearch";
            this.btnSearch.Size = new System.Drawing.Size(232, 25);
            this.btnSearch.TabIndex = 1;
            this.btnSearch.Text = "Search";
            this.btnSearch.Click += new System.EventHandler(this.btnSearch_Click);
            // 
            // txtSearch
            // 
            this.txtSearch.Dock = System.Windows.Forms.DockStyle.Top;
            this.txtSearch.Location = new System.Drawing.Point(0, 0);
            this.txtSearch.Name = "txtSearch";
            this.txtSearch.Size = new System.Drawing.Size(232, 21);
            this.txtSearch.TabIndex = 2;
            this.txtSearch.GotFocus += new System.EventHandler(this.txtSearch_GotFocus);
            this.txtSearch.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtSearch_KeyPress);
            this.txtSearch.LostFocus += new System.EventHandler(this.txtSearch_LostFocus);
            // 
            // tabIndex
            // 
            this.tabIndex.Controls.Add(this.lbIndex);
            this.tabIndex.Controls.Add(this.btnGo);
            this.tabIndex.Controls.Add(this.txtIndex);
            this.tabIndex.Location = new System.Drawing.Point(0, 0);
            this.tabIndex.Name = "tabIndex";
            this.tabIndex.Size = new System.Drawing.Size(232, 242);
            this.tabIndex.Text = "Index";
            // 
            // lbIndex
            // 
            this.lbIndex.Dock = System.Windows.Forms.DockStyle.Fill;
            this.lbIndex.Location = new System.Drawing.Point(0, 48);
            this.lbIndex.Name = "lbIndex";
            this.lbIndex.Size = new System.Drawing.Size(232, 184);
            this.lbIndex.TabIndex = 1;
            this.lbIndex.SelectedIndexChanged += new System.EventHandler(this.lbIndex_SelectedIndexChanged);
            // 
            // btnGo
            // 
            this.btnGo.Dock = System.Windows.Forms.DockStyle.Top;
            this.btnGo.Location = new System.Drawing.Point(0, 21);
            this.btnGo.Name = "btnGo";
            this.btnGo.Size = new System.Drawing.Size(232, 27);
            this.btnGo.TabIndex = 0;
            this.btnGo.Text = "Go";
            this.btnGo.Click += new System.EventHandler(this.btnGo_Click);
            // 
            // txtIndex
            // 
            this.txtIndex.Dock = System.Windows.Forms.DockStyle.Top;
            this.txtIndex.Location = new System.Drawing.Point(0, 0);
            this.txtIndex.Name = "txtIndex";
            this.txtIndex.Size = new System.Drawing.Size(232, 21);
            this.txtIndex.TabIndex = 2;
            this.txtIndex.TextChanged += new System.EventHandler(this.txtIndex_TextChanged);
            this.txtIndex.GotFocus += new System.EventHandler(this.txtIndex_GotFocus);
            this.txtIndex.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtIndex_KeyPress);
            this.txtIndex.LostFocus += new System.EventHandler(this.txtIndex_LostFocus);
            // 
            // PrgBar
            // 
            this.PrgBar.Dock = System.Windows.Forms.DockStyle.Bottom;
            this.PrgBar.Location = new System.Drawing.Point(0, 242);
            this.PrgBar.Name = "PrgBar";
            this.PrgBar.Size = new System.Drawing.Size(236, 20);
            // 
            // openFileDialog1
            // 
            this.openFileDialog1.Filter = "All Help Files|*.chm;*.hxs|CHM Help Files|*.chm|HXS Help Files|*.HXS";
            // 
            // lbInfo1
            // 
            this.lbInfo1.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
            this.lbInfo1.Dock = System.Windows.Forms.DockStyle.Top;
            this.lbInfo1.Location = new System.Drawing.Point(0, 0);
            this.lbInfo1.Name = "lbInfo1";
            this.lbInfo1.Size = new System.Drawing.Size(236, 139);
            // 
            // lbInfo2
            // 
            this.lbInfo2.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
            this.lbInfo2.Dock = System.Windows.Forms.DockStyle.Top;
            this.lbInfo2.Location = new System.Drawing.Point(0, 139);
            this.lbInfo2.Name = "lbInfo2";
            this.lbInfo2.Size = new System.Drawing.Size(236, 56);
            // 
            // lbInfo3
            // 
            this.lbInfo3.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(192)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
            this.lbInfo3.Dock = System.Windows.Forms.DockStyle.Fill;
            this.lbInfo3.Location = new System.Drawing.Point(0, 195);
            this.lbInfo3.Name = "lbInfo3";
            this.lbInfo3.Size = new System.Drawing.Size(236, 67);
            // 
            // PPCHelpReader
            // 
            this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
            this.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(1)))), ((int)(((byte)(192)))), ((int)(((byte)(255)))));
            this.ClientSize = new System.Drawing.Size(236, 262);
            this.Controls.Add(this.PrgBar);
            this.Controls.Add(this.lbInfo3);
            this.Controls.Add(this.lbInfo2);
            this.Controls.Add(this.lbInfo1);
            this.Controls.Add(this.tabControl1);
            this.Menu = this.mainMenu1;
            this.Name = "PPCHelpReader";
            this.Paint += new System.Windows.Forms.PaintEventHandler(this.PPCHelpReader_Paint);
            this.tabControl1.ResumeLayout(false);
            this.tabContents.ResumeLayout(false);
            this.tabSearch.ResumeLayout(false);
            this.tabIndex.ResumeLayout(false);
            this.ResumeLayout(false);

		}
		#endregion

		private void LoadParams()
		{
			RegistryKey RegKey=null;
			try
			{
				RegKey=Registry.CurrentUser.CreateSubKey(@"Software\PPCHelpReader.NET");
				
				bool bBool=false;
				int iInt=Convert.ToInt32(RegKey.GetValue("WipeTempDir",0));
				if (iInt!=0)
					bBool=true;
				bWipeTempDir=bBool;

				TempDir=Convert.ToString(RegKey.GetValue("TempDir",TempDirDefault));				
			}
			catch
			{
			}
			if (TempDir=="")
				TempDir=TempDirDefault;

			TempDir+=@"\HelpReaderTemp";
		}

		static string Program="";
        /// <summary>
        /// Registers the type of the file.
        /// </summary>
        /// <param name="FileExt">The file ext.</param>
        /// <param name="IconNumber">The icon number.</param>
		private static void RegisterFileType(string FileExt, int IconNumber)
		{
			if (Program=="")
			{
				Assembly asm=Assembly.GetExecutingAssembly();
				AssemblyName asmName=asm.GetName();
				Program=asmName.CodeBase;
			}

			RegistryKey RegKey=Registry.ClassesRoot.OpenSubKey(@"\",true);
			RegKey.CreateSubKey("."+FileExt).SetValue("",FileExt+"File");
			RegistryKey RegKey2=RegKey.CreateSubKey(FileExt+"File");
			RegKey2.SetValue("","Help File");
			RegKey2.CreateSubKey("DefaultIcon").SetValue("",Program+","+IconNumber.ToString());
			RegKey2.CreateSubKey(@"Shell\Open\Command").SetValue("","\""+Program+"\" \"%1\"");
		}

		/// <summary>
		/// The main entry point for the application.
		/// </summary>		
		static void Main(string[] args) 
		{
			RegisterFileType("chm", 0);
			RegisterFileType("chw", 0);
			RegisterFileType("chi", 0);
			RegisterFileType("chq", 0);
			RegisterFileType("hxs", 0);
			RegisterFileType("hxi", 0);
			RegisterFileType("msh", 0);
			
			PPCHelpReader app=null;
			try
			{
				app=new PPCHelpReader(args);
				Application.Run(app);
			}
			catch(Exception e)
			{
				string Msg="PPCHelpReader V";
				Assembly execAssembly= Assembly.GetExecutingAssembly();			
				Msg+=execAssembly.GetName().Version.ToString(3);
				Msg+="\n\rException Message : "+e.Message;

				MessageBox.Show(Msg);
				Application.Exit();
			}
			finally
			{
				app.Close();
				app.Dispose();
				app=null;
			}
		}

		#region Menu Options
		#region FileOpen
		private void mnuOpen_Click(object sender, System.EventArgs e)
		{
			if (helpSystem!=null)
				helpSystem=null;

            string FileName = "";            
            if (openFileDialog1.ShowDialog() == DialogResult.OK)
            {
                Cursor.Current = Cursors.WaitCursor;
                FileName = openFileDialog1.FileName;

                FileInfo Fi = new FileInfo(FileName);
                SaveInitialDir(Fi.DirectoryName);
                Update();
                OpenHelpFile(Fi);
                Fi = null;

                Cursor.Current = Cursors.Default;
            }            
		}

		private string GetInitialDir()
		{
			string DefaultDir=@"\My Documents";
			string Dir=DefaultDir;
			RegistryKey RegKey=null;
			try
			{
				RegKey=OpenNETCF.Win32.Registry.CurrentUser.CreateSubKey(@"Software\PPCHelpReader.NET");
				Dir=RegKey.GetValue("HelpReaderDir",DefaultDir).ToString();
				RegKey.Close();
			}
			catch(Exception)
			{
				Dir=DefaultDir;
			}	
			return Dir;
		}

		private void SaveInitialDir(string Dir)
		{
			OpenNETCF.Win32.RegistryKey RegKey=null;
			try
			{
				RegKey=OpenNETCF.Win32.Registry.CurrentUser.CreateSubKey(@"Software\PPCHelpReader.NET");
				RegKey.SetValue("HelpReaderDir",Dir);
				RegKey.Close();
			}
			catch(Exception)
			{
			}
		}
		#endregion	

		private void mnuClose_Click(object sender, System.EventArgs e)
		{
			tabControl1.Enabled=false;
			tabControl1.Visible=false;			
			Close();

			// Delete old Temp Directory & files
			if (this.bWipeTempDir)
			{
				try
				{
					Directory.Delete(TempDir,true);
				}
				catch(Exception ex)
				{
					Debug.WriteLine(ex.Message);
				}
			}
		}

		private void mnuAbout_Click(object sender, System.EventArgs e)
		{            
            // Dialogs.ShowDialog(new About(),this);
            new About().ShowDialog();
            this.Show();
            this.Activate();
            this.Refresh();
		}
		#endregion	

		#region Open Help File
        /// <summary>
        /// OpenHelpFile - Opens the specified Help file. Resets the tab pages content
        /// </summary>
        /// <param name="FileInfo">The file info.</param>
		private void OpenHelpFile(FileInfo FileInfo)
		{		
			fi=FileInfo;

			if (!File.Exists(fi.FullName))
			{
				// Remove from MRU
				mruMenu.RemoveFile(fi.FullName);

				// Save MRU List to registry.
				mruMenu.SaveToRegistry();

				// Show message box
				MessageBox.Show("Failed to find "+FileInfo.FullName);
				return;
			}

			mruMenu.AddFile(fi.FullName);
			mruMenu.MakeFileFirst(fi.FullName);
			mruMenu.SaveToRegistry();
            mnuRecent.Enabled = (mnuRecent.MenuItems.Count > 0);

			Cursor.Current=Cursors.WaitCursor;
			if (helpSystem!=null)
				helpSystem=null;
					
			string Name=FileInfo.Name.ToLower();
			Name=Name.Substring(0,1).ToUpper()+Name.Substring(1);
			LocationString=Name;
			
			// Disable TabControl to show Load Progress Controls
			ShowProgress(true);			

			// Remove all Tab Pages
			tabControl1.TabPages.Clear();			
			Update();
			
			// Reset Contents 
			m_bContentsInit=false;
			tvContents.Nodes.Clear();			

			// Reset Index
			m_bIndexInit=false;
			txtIndex.Text="";
			lbIndex.Items.Clear();

			// Reset Search
			m_bSearchInit=false;
			txtSearch.Text="";			
			lvSearch.Items.Clear();
						
			// Init HTMLHelp System
			helpSystem=new MSHelpLib.HelpSystem();
			helpSystem.StatusHandlerEvent+=new StatusHandler(helpSystem_StatusHandlerEvent);
			helpSystem.ProgressHandlerEvent+=new ProgressHandler(helpSystem_ProgressHandlerEvent);
									
			int Flags=(int)(LoadFlags.LoadDumpFile);
		
			// Read Flags from registry
			RegistryKey RegKey=null;
			try
			{				
				RegKey=Registry.CurrentUser.OpenSubKey(@"Software\PPCHelpReader.NET");
				if (RegKey!=null)
				{
					int iInt=Convert.ToInt32(RegKey.GetValue("AllowCHB",1));
					if (iInt!=0)
						Flags+=(int)LoadFlags.SaveDumpFile;

					iInt=Convert.ToInt32(RegKey.GetValue("WipeTempDir",0));
					if (iInt!=0)
						Flags+=(int)LoadFlags.WipeTempDir;
				
					iInt=Convert.ToInt32(RegKey.GetValue("CreateSearch",0));
					if (iInt==0)
						Flags+=(int)LoadFlags.CreateSearchIndexOnFirstUseAndSave;
					if (iInt==1)
						Flags+=(int)LoadFlags.CreateSearchIndexOnLoad;						
					
					iInt=Convert.ToInt32(RegKey.GetValue("RemoveScriptTags",1));
					if (iInt!=0) Flags+=(int)LoadFlags.RemoveScriptTags;
					
					iInt=Convert.ToInt32(RegKey.GetValue("RemoveXMLTags",1));
					if (iInt!=0) Flags+=(int)LoadFlags.RemoveXMLTags;

					iInt=Convert.ToInt32(RegKey.GetValue("RemoveDisplayNone",1));
					if (iInt!=0) Flags+=(int)(LoadFlags.RemoveDisplayNone|LoadFlags.RemoveSizeNone);

					iInt=Convert.ToInt32(RegKey.GetValue("UseHTTPDecode",1));
					if (iInt!=0) Flags+=(int)LoadFlags.HTTPDecode;

                    iInt = Convert.ToInt32(RegKey.GetValue("IgnoreImages", 0));
                    if (iInt != 0) Flags += (int)LoadFlags.IgnoreImages;
				}
			}
			finally
			{
				if (RegKey!=null)
					RegKey.Close();
			}			

			// Open Help File
			helpSystem.Open(FileInfo.FullName,Flags);
			
			// Init the Tab Control
			tabControl1.TabPages.Clear();
			if (helpSystem.HasTableOfContents)	
			{				
				tabControl1.TabPages.Add(tabContents);				
				tabContents.Text="Contents";
				Update();
			}
			if (helpSystem.HasIndex)
			{
				tabControl1.TabPages.Add(tabIndex);
				tabIndex.Text="Index";
				Update();
			}
			if (helpSystem.CanSearch)		
			{
				tabControl1.TabPages.Add(tabSearch);
				tabSearch.Text="Search";
				Update();
			}			

			ShowProgress(false);			

			// Select Contents as starting tab
			tabControl1.SelectedIndex=-1;
			if (tabControl1.TabPages.Count>0)
				tabControl1.SelectedIndex=tabControl1.TabPages.IndexOf(this.tabContents);

            if (this.bWipeTempDir)
                WipeTempDir();

			// Restore Cursor
			Cursor.Current=Cursors.Default;
		}

        private void WipeTempDir()
        {
            // Delete old Temp Directory & files
            try
            {
                Directory.Delete(TempDir, true);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.Message);
            }
        }
		#endregion

		#region Display Selected URL
		
		private string CheckURL(string URL)
		{
			if (URL==null)
				return null;
			if (URL=="")
				return "";

			string newURL=URL;			
			do
			{				
				if (newURL.StartsWith(@"../"))
					newURL=newURL.Substring(3);					
				else 
					break;
			}
			while(true);
			if (!newURL.StartsWith("/"))
				newURL="/"+newURL;
			return newURL;
		}

		private TOCItem FindTOCItem(string Url)
		{
			TOCItem item=(TOCItem)tvContents.Nodes[0].Tag;

			Url=CheckURL(Url);
			while (item!=null)
			{
				string LocalUrl=CheckURL(item.Local);
				if (Url.Length<=LocalUrl.Length)
				{										
					if (LocalUrl.IndexOf(Url)>=LocalUrl.Length-Url.Length)
						return item;
				}
				item=item.Next;
			}
			return null;
		}

		private void DisplayPage(string _Url, string Title)
		{
			DisplayPage(_Url, Title, false,"");
		}

        private void DisplayPage(string _Url, string Title, string ArticalName)
        {
            DisplayPage(_Url, Title, false, ArticalName);
        }

        private void DisplayPage(string _Url, string Title, bool bEnableNavButtons, string ArticalName)
		{
			string Url=_Url;
			bool bQuit=false;
			// string HTMLText="";
			TOCItem item=null;
			            
			if (_Url=="")
				return;
			
			string LocalTitle="";
			if (tabControl1.TabPages.Count>0)
			{
				if (tabControl1.SelectedIndex==tabControl1.TabPages.IndexOf(tabContents))
				{
					TOCItem Item=(TOCItem)tvContents.SelectedNode.Tag;			
					if (Item!=null)
						LocalTitle=tvContents.SelectedNode.Text;
				}
			}

			do
			{
				HTMLView View=new HTMLView();
				View.NavButtons(bEnableNavButtons);

				m_bInLoop=true;
				Cursor.Current=Cursors.WaitCursor;
               
				ShowProgress(true);
                MSHelpLib.HelpPageProcessing hpp = new HelpPageProcessing(helpSystem, Url, this.TempDir, ArticalName);
				string FileName=hpp.Process();
				ShowProgress(false);

				View.SetUrl(@"file://"+FileName);
				View.SetTitle(Title+LocalTitle);				

				bool bLoop=false;
				do
				{
					bLoop=false;
					
					Cursor.Current=Cursors.Default;                    
					// Dialogs.ShowDialog(View,this);					
                    View.ShowDialog();
                    this.Show();
                    this.Activate();
                    this.Refresh();
					View.Text="PPCHelpReader";
					Cursor.Current=Cursors.WaitCursor;

					TreeNode SNode=null;
					switch(View.WhereNext)
					{
						case EnumWhereNext.Next : 												
							SNode=tvContents.SelectedNode;
							item=(TOCItem)SNode.Tag;
							if (item!=null)
							{
								while((item!=null) && (item.Next!=null))
								{
									Url=item.Next.Url;								
									if (!Url.EndsWith("::/"))								
										break;
									item=item.Next;
								}
								if (item.Next!=null)
								{
									tvContents.SelectedNode=item.Next.treeNode;
									LocalTitle=item.Next.Name;
                                    ArticalName = item.Next.Name;
								}
							}
							break;

						case EnumWhereNext.Prev : 
							SNode=tvContents.SelectedNode;
							item=(TOCItem)SNode.Tag;
							if (item!=null)
							{
								while ((item!=null) && (item.Prev!=null))
								{
									Url=item.Prev.Url;
									if (!Url.EndsWith("::/"))								
										break;
									item=item.Prev;
								}
								if (item.Prev!=null)
								{
									tvContents.SelectedNode=item.Prev.treeNode;
									LocalTitle=item.Prev.Name;
                                    ArticalName = item.Prev.Name;
								}
							}
							break;

						case EnumWhereNext.Close: 
							bQuit=true;
							break;

						case EnumWhereNext.None : 
							bQuit=true;
							break;

						case EnumWhereNext.Link:												
							Url=View.Link;

							// Handle Jump to anchor within local HTML File.
							if (Url.StartsWith("#"))
							{
								bLoop=true;
								View.SetAnchor(Url.Substring(1));
								LocalTitle="";
                                ArticalName = "";
							}
							else
							{
								bLoop=false;
								item=FindTOCItem(Url);
								if (item!=null)
								{
									tvContents.SelectedNode=item.treeNode;
									LocalTitle=item.Name;
                                    ArticalName = item.Name;
								}
							}
							break;
					}
				}
				while (bLoop==true);
				View.Dispose();
				View=null;

                this.Show();
                this.Activate();
                this.Refresh();
			}
			while(bQuit==false);
			m_bInLoop=false;	

			Cursor.Current=Cursors.Default;
		}
		#endregion

		#region Tab Control Handling
		private void tabControl1_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if (helpSystem==null)
				return;

			Cursor.Current=Cursors.WaitCursor;
			if (tabControl1.SelectedIndex==tabControl1.TabPages.IndexOf(tabContents))
			{
				if (!m_bContentsInit)
				{
					if (helpSystem.HasTableOfContents)
					{		
						MSHelper.FillTree(helpSystem,tvContents);
						tabContents.Show();				
							
						m_bMovingSelection=true;
						tvContents.SelectedNode=tvContents.Nodes[0];
						m_bMovingSelection=false;			
						m_bContentsInit=true;
					}
				}
			}

			if (tabControl1.SelectedIndex==tabControl1.TabPages.IndexOf(tabIndex))
			{	
				if (!m_bIndexInit)
				{
					lbIndex.Items.Clear();				
					lbIndex.DisplayMember="Title";

					if (helpSystem.HasIndex)
					{	
						MSHelpLib.BaseCode.MSHelper.BuildIndex(helpSystem.Index.KLinks,lbIndex);
					}

					if (lbIndex.Items.Count>0)
					{
						m_bMovingSelection=true;					
						lbIndex.SelectedIndex=0;
						m_bMovingSelection=false;			
					}

					m_bIndexInit=true;
				}
			}

			if (tabControl1.SelectedIndex==tabControl1.TabPages.IndexOf(tabSearch))
			{				
				if (!m_bSearchInit)
				{
					lvSearch.Items.Clear();
					
					if (helpSystem.CanSearch)
					{				
						ShowProgress(true);						
												
						PrgBar.Maximum=helpSystem.NumberOfFiles;
						helpSystem.InitSearch();
						m_bSearchInit=true;
						
						ShowProgress(false);
					}
				}
			}
			
			Cursor.Current=Cursors.Default;
		}
		#endregion

		#region InputPanel Handling
		private void txtIndex_GotFocus(object sender, System.EventArgs e)
		{
			if (inputPanel1!=null)
				this.inputPanel1.Enabled=true;
		}

		private void txtIndex_LostFocus(object sender, System.EventArgs e)
		{
			if (inputPanel1!=null)
				this.inputPanel1.Enabled=false;
		}

		private void txtSearch_GotFocus(object sender, System.EventArgs e)
		{		
			if (inputPanel1!=null)
				this.inputPanel1.Enabled=true;
		}

		private void txtSearch_LostFocus(object sender, System.EventArgs e)
		{
			if (inputPanel1!=null)
				this.inputPanel1.Enabled=false;
		}

		private void inputPanel1_EnabledChanged(object sender, System.EventArgs e)
		{
			if (inputPanel1!=null)
			{
				if (inputPanel1.Enabled == false)
				{
					// The SIP is disabled, so the height of the tab control
					// is set to its original height with a variable (TabOriginalHeight) ,
					// which is determined during initialization of the form.
					VisibleRect = inputPanel1.VisibleDesktop;
					tabControl1.Height = TabOriginalHeight;				
				}
				else
				{
					// The SIP is enabled, so the height of the tab control 
					// is set to the height of the visible desktop area.
					VisibleRect = inputPanel1.VisibleDesktop;
					tabControl1.Height = VisibleRect.Height;
				}
				tvContents.Height = tabContents.Bottom - tvContents.Top-2;
				lbIndex.Height = tabIndex.Bottom - lbIndex.Top-2;
				lvSearch.Height = tabSearch.Bottom-lvSearch.Top-2;
			}
		}
		#endregion

		#region Contents Handling
        /// <summary>
        /// Handles the AfterSelect event of the tvContents control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.Windows.Forms.TreeViewEventArgs"/> instance containing the event data.</param>
		private void tvContents_AfterSelect(object sender, System.Windows.Forms.TreeViewEventArgs e)
		{
			if (m_bMovingSelection)
				return;

			if ((e.Action==TreeViewAction.Expand)||(e.Action==TreeViewAction.Collapse)||(e.Action==TreeViewAction.Unknown))
				return;			

			if (!m_bInLoop)
			{
				TOCItem Item=(TOCItem)tvContents.SelectedNode.Tag;				
				string Title=""; // tvContents.SelectedNode.Text;
				TreeNode tn=e.Node.Parent;
				while (tn!=null)
				{
					Title=tn.Text+"\\"+Title;
					tn=tn.Parent;
				}				
				string FileName=fi.Name.ToLower();
				FileName=FileName.Substring(0,1).ToUpper()+FileName.Substring(1);
				Title=FileName+"\\"+Title;

				if (Item.Url.EndsWith("::/"))
					return;

				DisplayPage(Item.Url,Title,true,Item.Name);
			}
		}
		#endregion

		#region Index Handling
		private void txtIndex_TextChanged(object sender, System.EventArgs e)
		{
			Cursor.Current=Cursors.WaitCursor;
			int idx = -1;
			int Len=txtIndex.Text.Length;
			string szText=txtIndex.Text.Trim().ToLower();		
			foreach(IndexItem2 item in lbIndex.Items)
			{				
				idx++;
				string str=item.Title;
				str=str.ToLower();

				if (txtIndex.Text.Length>str.Length)
					continue;

				if (str.Substring(0,Len)==szText)
				{					
					m_bMovingSelection=true;
					lbIndex.SelectedIndex = idx;
					m_bMovingSelection=false;
					Cursor.Current=Cursors.Default;
					return;
				}				
			}
			Cursor.Current=Cursors.Default;
		}

		private void txtIndex_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
		{
			if( e.KeyChar == (char)Keys.Enter )
			{
				if( lbIndex.SelectedIndex >= 0)
				{
					lbIndex_SelectedIndexChanged(sender,EventArgs.Empty);					
					e.Handled = true;
				}
			}
		}

		private void lbIndex_SelectedIndexChanged(object sender, System.EventArgs e)
		{
			if (m_bMovingSelection)
				return;			

			// Display Page				
			IndexItem2 item=(IndexItem2)lbIndex.SelectedItem;			
			if (item==null)
				return;
			string FileName=fi.Name.ToLower();
			FileName=FileName.Substring(0,1).ToUpper()+FileName.Substring(1);
								
			if ((item!=null) && (item.FullURL!=""))
				DisplayPage(item.FullURL,FileName+"\\"+item.Title);
		}
		#endregion

		#region Search Handling
		private void btnSearch_Click(object sender, System.EventArgs e)
		{			
			lvSearch.Items.Clear();			
			if (txtSearch.Text=="")
				return;		

			if (!helpSystem.CanSearch)
				return;
		
			Cursor.Current=Cursors.WaitCursor;			
			SearchResultsTable Hits=helpSystem.PerformSearch(txtSearch.Text);

			if (Hits!=null)
			{
				Hits.DefaultView.RowFilter = "";
				Hits.DefaultView.Sort="rank desc";
			}
			SetResults(Hits);			
			
			Cursor.Current=Cursors.Default;
		}

		private void lvSearch_ItemActivate(object sender, System.EventArgs e)
		{
			if (lvSearch.SelectedIndices.Count!=1)
				return;
			
			SearchResultsRow row=(SearchResultsRow)_hits.DefaultView[lvSearch.SelectedIndices[0]].Row;
			string URL=row.URL;
			string Title=row.Title;
			
			string FileName=fi.Name.ToLower();
			FileName=FileName.Substring(0,1).ToUpper()+FileName.Substring(1);

            DisplayPage(URL, FileName + "\\" + Title, Title);
		}

		private void txtSearch_KeyPress(object sender, System.Windows.Forms.KeyPressEventArgs e)
		{
			if( e.KeyChar == (char)Keys.Enter )
			{
				// Do Search
				btnSearch_Click(sender,e);
			}
		}

		/// <summary>
		/// Updates the search results with the records of the given data table
		/// </summary>
		/// <param name="hits">hits table</param>
		public void SetResults(SearchResultsTable hits)
		{
			lvSearch.Items.Clear();

			_hits = hits;

			if(_hits != null)
			{
				_hits.DefaultView.RowFilter="";

				for(int i=0; i<_hits.DefaultView.Count; i++)
				{	
					SearchResultsRow row=(SearchResultsRow)_hits.DefaultView[i].Row;
					ListViewItem lvItem = new ListViewItem(row.Title);

					string Location=row.Location;
					string []parts=Location.Split('\\');
					lvItem.SubItems.Add( parts[parts.Length-1]);
					lvItem.SubItems.Add( row.Rank.ToString());
					lvSearch.Items.Add( lvItem );
				}				
			} 
			else 
			{
				MessageBox.Show("No results found");
			}
		}

		private void lvSearch_ColumnClick(object sender, System.Windows.Forms.ColumnClickEventArgs e)
		{
			string sSort = "Title " + (ascSort ? "ASC" : "DESC");

			if(e.Column == 1)
			{
				sSort = "Location " + (ascSort ? "ASC" : "DESC");
			}
			if(e.Column == 2)
			{
				sSort = "Rating " + (ascSort ? "ASC" : "DESC");
			}

			ascSort = !ascSort;

			if(_hits != null)
			{
				_hits.DefaultView.Sort = sSort;
				SetResults(_hits);
			}		
		}	
		#endregion

		#region Paint Handler
		private Bitmap m_BackgroundImage=null;

		private void MakeBackgroundImage()
		{
			// From 255,255,255 to 0,128,0
			m_BackgroundImage=new Bitmap(Width,1);
			double step=(double)255/(double)Width;
			for(int i=0;i<Width;i++)
			{				
				int r=255-Convert.ToInt32(step*i);
				int b=255-(Convert.ToInt32(step*i)/2);
				int g=r;					
				Color clr=Color.FromArgb(r,g,b);
				m_BackgroundImage.SetPixel(i,0,clr);
			}
		}

		private void PPCHelpReader_Paint(object sender, System.Windows.Forms.PaintEventArgs e)
		{
			if ((lbInfo1.Visible==false) && (tabControl1.Visible==false))
			{
				if (m_BackgroundImage==null) MakeBackgroundImage();			
				ImageAttributes ia=new ImageAttributes();
				e.Graphics.DrawImage(m_BackgroundImage,new Rectangle(0,0,Width,Height),0,0,Width,1,GraphicsUnit.Pixel, ia);
			}
		}
		#endregion

		#region Options Dialog
		private void mnuOptions_Click(object sender, System.EventArgs e)
		{
            // Dialogs.ShowDialog(new Options(),this);
            new Options().ShowDialog();
            this.Show();
            this.Activate();
            this.Refresh();

			LoadParams();
            WipeTempDir();
		}
		#endregion

		#region helpSystem File Load Progress Event Handlers
		private void helpSystem_StatusHandlerEvent(int Level, string Info)
		{
			if ((lbInfo1!=null) && (Level==0))
			{
				lbInfo1.Text=Info;
				lbInfo1.Update();
				this.Refresh();
			}
			if ((lbInfo2!=null) && (Level==1))
			{
				lbInfo2.Text=Info;
				lbInfo2.Update();			
				this.Refresh();			
			}
            if ((lbInfo3 != null) && (Level == 2))
            {
                lbInfo3.Text = Info;
                lbInfo3.Update();
                this.Refresh();
            }
		}

		private void helpSystem_ProgressHandlerEvent(int Value, int MaxValue)
		{
			if (PrgBar!=null)
			{
				PrgBar.Maximum=MaxValue;
				if (Value>PrgBar.Maximum) Value=PrgBar.Maximum;
				PrgBar.Value=(int)Value;
				PrgBar.Update();
				this.Refresh();
			}
		}
		#endregion

        /// <summary>
        /// Handles the Click event of the btnGo control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		private void btnGo_Click(object sender, System.EventArgs e)
		{
			if (lbIndex.SelectedItem==null)
				return;

			IndexItem2 item=(IndexItem2)lbIndex.SelectedItem;
			if (item.Url!="")
				DisplayPage(item.FullURL,item.Title,false,item.Title);
		}

        /// <summary>
        /// Handles the Click event of the menuLocation control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
		private void menuLocation_Click(object sender, System.EventArgs e)
		{
			if (LocationString!="")
				MessageBox.Show(LocationString,"Location");		
		}

        /// <summary>
        /// Shows the progress.
        /// </summary>
        /// <param name="bShowProgress">if set to <c>true</c> [b show progress].</param>
		private void ShowProgress(bool bShowProgress)
		{
			// Disable TabControl to show Load Progress Controls
			tabControl1.Enabled=!bShowProgress;
			tabControl1.Visible=!bShowProgress;			
			lbInfo1.Visible=bShowProgress;
			lbInfo2.Visible=bShowProgress;
            lbInfo3.Visible = bShowProgress;
			PrgBar.Visible=bShowProgress;

			if (bShowProgress)
			{
				lbInfo1.Text="Please Wait...";
				lbInfo2.Text="";
                lbInfo3.Text = "";
				PrgBar.Value=0;
				PrgBar.Maximum=100;
				PrgBar.Minimum=0;
			}
			Refresh();
		}		
	}
}
